package ua.races.command.implementation;

import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import ua.races.vo.Horse;
import ua.races.vo.Race;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class PrepareResultsCommand implements ServletCommand {
    private static final Logger log = Logger.getLogger(PrepareCoefsCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        Race race = null;
        RacesDaoImpl dao;
        List<Horse> horses = null;
        Long raceId = null;

        try {
            dao = (RacesDaoImpl) context.getAttribute("DAO");
            raceId = Long.parseLong(req.getParameter("raceId"));
            race = dao.findRaceById(raceId);
            horses = dao.findAllHorseInRace(race);
            req.setAttribute("race", race);
            req.setAttribute("horses", horses);
            log.info("horses and race for setResults.jsp are successfully prepared");
        } catch (SQLException e) {
            log.error(e);
            try {
                resp.sendRedirect("pipec.jsp");
            } catch (IOException fe) {
                log.fatal(fe);
            }
        } catch (Throwable e) {
            log.error(e);
        }


        try {
            context.getRequestDispatcher("/setResults.jsp").forward(req, resp);
        } catch (ServletException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }

    }
}